package database

import (
	"github.com/google/uuid"
	capi "github.com/hashicorp/consul/api"
)

type ConsulClient struct {
	Client *capi.Client
}

func NewConsulClient(addr string) *ConsulClient {
	// Get a new client
	cfg := capi.DefaultConfig()
	cfg.Address = addr

	client, err := capi.NewClient(cfg)
	if err != nil {
		panic(err)
	}

	return &ConsulClient{Client: client}
}

type GrpcConsul struct {
	Name    string
	Tags    []string
	Address string
	Port    int
}

func (c *ConsulClient) RegisterService(cfg GrpcConsul) error {
	registration := capi.AgentServiceRegistration{
		ID:      uuid.NewString(),
		Name:    cfg.Name,
		Port:    cfg.Port,
		Address: cfg.Address,
		Tags:    cfg.Tags,
	}
	return c.Client.Agent().ServiceRegister(&registration)
}
func GrpcConsulInit() {
	consul := NewConsulClient("14.103.151.136:8500")
	conf := GrpcConsul{
		Name: "shop-srv",
		Tags: []string{
			"shop-srv",
		},
		Address: "127.0.0.1",
		Port:    50051,
	}
	err := consul.RegisterService(conf)
	if err != nil {
		panic(err)
	}
	//flag.Parse()
	//// Set up a connection to the server.
	//conn, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	//if err != nil {
	//	log.Fatalf("did not connect: %v", err)
	//}

}
